/*
 * Copyright (C) 2014 Eduardo Pereira Montenegro <epereiramontenegro@gmail.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.googlecode.bambole.controller;

import com.googlecode.bambole.controller.util.JsfUtil;
import com.googlecode.bambole.controller.util.PaginationUtil;
import com.googlecode.bambole.domain.Organization;
import com.googlecode.bambole.domain.OrganizationNote;
import com.googlecode.bambole.domain.User;
import com.googlecode.bambole.facade.OrganizationNoteFacade;
import com.googlecode.bambole.util.SearchUtil;

import java.io.Serializable;
import java.util.Date;
import java.util.ResourceBundle;
import javax.ejb.EJB;
import javax.inject.Named;
import javax.enterprise.context.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;
import javax.inject.Inject;

@Named("organizationNoteController")
@SessionScoped
public class OrganizationNoteController implements Serializable {

    private OrganizationNote current;
    private DataModel items = null;

    @EJB
    private com.googlecode.bambole.facade.OrganizationNoteFacade ejbFacade;

    @EJB
    private com.googlecode.bambole.facade.OrganizationFacade organizationFacade;

    @Inject
    private com.googlecode.bambole.controller.OrganizationController organizationController;

    private PaginationUtil pagination;
    private Organization currentOrganization;
    private String remainderSearch;
    private String closedSearch;
    private String query;
    private boolean currentClosedValue;
    private int selectedItemIndex;
    private int recordCount;

    public OrganizationNoteController() {
    }

    public OrganizationNote getSelected() {
        if (current == null) {
            current = new OrganizationNote();
        }
        return current;
    }

    public void setSelected(OrganizationNote current) {
        this.current = current;
    }

    private OrganizationNoteFacade getFacade() {
        return ejbFacade;
    }

    public boolean isPaginationFromSearch() {
        return !getQuery().equals(getDefaultQuery());
    }

    public PaginationUtil getPagination() {
        if (pagination == null) {
            pagination = new PaginationUtil(10) {

                @Override
                public int getItemsCount() {
                    return getFacade().count(getQuery(), currentOrganization);
                }

                @Override
                public DataModel createPageDataModel() {
                    return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}, getQuery(), currentOrganization));
                }
            };
        }
        return pagination;
    }

    public String refreshList() {
        query = null;
        recreatePagination();
        recreateModel();
        return "list.xhtml?faces-redirect=true";
    }

    public String prepareList() {
        recreateModel();
        return "list.xhtml?faces-redirect=true";
    }

    public String prepareView() {
        if (current == null) {
            JsfUtil.addErrorMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("NoRecordSelected"));
            return null;
        }

        recordCount = getFacade().count(getQuery(), currentOrganization);

        return "view.xhtml?faces-redirect=true";
    }

    public String prepareCreate() {
        current = new OrganizationNote();
        current.setOrganization(currentOrganization);
        return "create.xhtml?faces-redirect=true";
    }

    public String create() {

        if (!validateRecord()) {
            return null;
        }

        if (!updateCurrentOrganization()) {
            return null;
        }

        Date date = new Date();
        User user = (User) JsfUtil.getSessionParameter("user");
        current.setCreated(date);
        current.setCreatedBy(user);
        current.setUpdated(date);
        current.setUpdatedBy(user);

        try {
            getFacade().create(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("RecordSaved"));
            return "view.xhtml?faces-redirect=true";
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("PersistenceError"));
            return null;
        }
    }

    public String prepareEdit() {
        if (current == null) {
            JsfUtil.addErrorMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("NoRecordSelected"));

            return null;
        }
        currentClosedValue = current.isClosed();

        return "edit.xhtml?faces-redirect=true";
    }

    public String update() {

        if (!validateRecord()) {
            return null;
        }

        if (!updateCurrentOrganization()) {
            return null;
        }

        current.setUpdated(new Date());
        current.setUpdatedBy((User) JsfUtil.getSessionParameter("user"));

        try {
            getFacade().edit(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("RecordSaved"));
            return "view.xhtml?faces-redirect=true";
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("PersistenceError"));
            return null;
        }
    }

    public String destroy() {
        if (current == null) {
            JsfUtil.addErrorMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("NoRecordSelected"));
            return null;
        }
        performDestroy();
        recreatePagination();
        recreateModel();
        return "list.xhtml?faces-redirect=true";
    }

    private void performDestroy() {
        try {
            getFacade().remove(current);
            if (updateCurrentOrganization()) {
                JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("RecordDeleted"));
            }
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("PersistenceError"));
        }
    }

    public DataModel getItems() {
        if (items == null) {
            items = getPagination().createPageDataModel();
        }
        return items;
    }

    private void recreateModel() {
        items = null;
    }

    private void recreatePagination() {
        pagination = null;
    }

    public String next() {
        getPagination().nextPage();
        recreateModel();
        return "list.xhtml?faces-redirect=true";
    }

    public String previous() {
        getPagination().previousPage();
        recreateModel();
        return "list.xhtml?faces-redirect=true";
    }

    public SelectItem[] getItemsAvailableSelectMany() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), false);
    }

    public SelectItem[] getItemsAvailableSelectOne() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), true);
    }

    public OrganizationNote getOrganizationNote(java.lang.Integer id) {
        return ejbFacade.find(id);
    }

    public void setSelectedItemIndex(int selectedItemIndex) {
        this.selectedItemIndex = selectedItemIndex + pagination.getPageFirstItem();
    }

    public boolean isHasNextRecord() {
        return selectedItemIndex + 2 <= recordCount;
    }

    public boolean isHasPreviousRecord() {
        return selectedItemIndex > 0;
    }

    public String nextItem() {

        selectedItemIndex++;

        if (selectedItemIndex < recordCount) {
            current = getFacade().findRange(new int[]{selectedItemIndex, selectedItemIndex}, getQuery(), currentOrganization).get(0);
        }

        return "view.xhtml?faces-redirect=true";
    }

    public String previousItem() {

        selectedItemIndex--;

        if (selectedItemIndex >= 0) {
            current = getFacade().findRange(new int[]{selectedItemIndex, selectedItemIndex}, getQuery(), currentOrganization).get(0);
        }

        return "view.xhtml?faces-redirect=true";
    }

    private boolean validateRecord() {

        boolean retVal = true;

        if (!current.isClosed() && current.getRemainder() != null && current.getRemainder().before(new Date())) {
            JsfUtil.addErrorMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("NoteRemainderMustBeGreaterThanToday"));

            retVal = false;
        }

        if (current.isClosed() && currentClosedValue) {
            JsfUtil.addErrorMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("ClosedNotesCannotBeChanged"));

            retVal = false;
        }

        return retVal;
    }

    private String getQuery() {
        return query == null ? getDefaultQuery() : query;
    }

    private String getDefaultQuery() {
        return "SELECT o FROM OrganizationNote o WHERE o.organization = :organization";
    }

    public String prepareSearch() {
        current = new OrganizationNote();
        current.setOrganization(currentOrganization);

        remainderSearch = null;
        closedSearch = null;

        return "search.xhtml?faces-redirect=true";
    }

    public String performSearch() {

        boolean queryAddAnd = false;

        boolean queryContainsErrors = false;

        query = getDefaultQuery();

        if ((current.getDescription() != null && !current.getDescription().isEmpty())
                || (getRemainderSearch() != null && !getRemainderSearch().isEmpty())
                || (getClosedSearch() != null && !getClosedSearch().isEmpty())) {

            query = query + " AND ";

            if (current.getDescription() != null && !current.getDescription().isEmpty()) {
                queryAddAnd = true;
                query = query + "o.description LIKE \'%" + current.getDescription() + "%\'";
            }

            if (getRemainderSearch() != null && !getRemainderSearch().isEmpty()) {
                String remainderSearchClause = SearchUtil.getQueryClause("FUNC(\'DATE\',o.remainder)", getRemainderSearch(), 'd', queryAddAnd);
                if (!remainderSearchClause.equals("*")) {
                    query = query + remainderSearchClause;
                    queryAddAnd = true;
                } else {
                    queryContainsErrors = true;
                }
            }

            if (getClosedSearch() != null && !getClosedSearch().isEmpty()) {
                String closedSearchSearchClause = SearchUtil.getQueryClause("o.closed", getClosedSearch(), 'b', queryAddAnd);
                if (!closedSearchSearchClause.equals("*")) {
                    query = query + closedSearchSearchClause;
                } else {
                    queryContainsErrors = true;
                }
            }
        }

        if (queryContainsErrors) {
            JsfUtil.addErrorMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("InvalidSearchCriteria"));

            return prepareSearch();
        } else {
            recreatePagination();
            recreateModel();

            return "list.xhtml?faces-redirect=true";
        }
    }

    public String getRemainderSearch() {
        return remainderSearch;
    }

    public void setRemainderSearch(String remainderSearch) {
        this.remainderSearch = remainderSearch;
    }

    public String getClosedSearch() {
        return closedSearch;
    }

    public void setClosedSearch(String closedSearch) {
        this.closedSearch = closedSearch;
    }

    public Organization getCurrentOrganization() {
        return currentOrganization;
    }

    public void setCurrentOrganization(Organization organization) {
        currentOrganization = organization;
        query = getDefaultQuery();
        recreatePagination();
        recreateModel();
    }

    public String prepareCurrentOrganizationView() {
        if (updateCurrentOrganization()) {
            organizationController.setSelected(currentOrganization);
            return "/app/organization/view.xhtml?faces-redirect=true";
        } else {
            return null;
        }
    }

    private boolean updateCurrentOrganization() {
        if (currentOrganization == null) {
            JsfUtil.addErrorMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("NoRecordSelected"));
            return false;
        }

        currentOrganization.setOrganizationNoteList(getFacade().findByOrganization(currentOrganization));

        try {
            organizationFacade.edit(currentOrganization);
            return true;
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("PersistenceError"));
            return false;
        }
    }

    @FacesConverter(forClass = OrganizationNote.class)
    public static class OrganizationNoteControllerConverter implements Converter {

        @Override
        public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
            if (value == null || value.length() == 0) {
                return null;
            }
            OrganizationNoteController controller = (OrganizationNoteController) facesContext.getApplication().getELResolver().
                    getValue(facesContext.getELContext(), null, "organizationNoteController");
            return controller.getOrganizationNote(getKey(value));
        }

        java.lang.Integer getKey(String value) {
            java.lang.Integer key;
            key = Integer.valueOf(value);
            return key;
        }

        String getStringKey(java.lang.Integer value) {
            StringBuilder sb = new StringBuilder();
            sb.append(value);
            return sb.toString();
        }

        @Override
        public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
            if (object == null) {
                return null;
            }
            if (object instanceof OrganizationNote) {
                OrganizationNote o = (OrganizationNote) object;
                return getStringKey(o.getId());
            } else {
                throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + OrganizationNote.class.getName());
            }
        }

    }

}
